package com.xiaoguozi.web.handler;

        import javax.servlet.ServletRequest;
        import javax.servlet.ServletResponse;
        import javax.servlet.http.HttpServletRequest;
        import java.io.IOException;
        import java.lang.reflect.InvocationTargetException;
        import java.lang.reflect.Method;

public class HandlerMapping {
    private String uri;
    private Class<?> cls;
    private Method method;
    private String[] args;

    public HandlerMapping(String uri, Class<?> cls, Method method, String[] args) {
        this.uri = uri;
        this.cls = cls;
        this.method = method;
        this.args = args;
    }

    public boolean handle(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalAccessException, InstantiationException, InvocationTargetException, IOException {
        String requestUri = ((HttpServletRequest) servletRequest).getRequestURI();
        if (!uri.equals(requestUri)) {
            return false;
        }
        Object[] parameters = new Object[args.length];
        for (int i = 0; i < args.length; i++) {
            parameters[i] = servletRequest.getParameter(args[i]);
        }
        Object ctl = cls.newInstance();
        Object respone = method.invoke(ctl, parameters);
        servletResponse.getWriter().println(respone.toString());
        return true;
    }
}
